<template>
	<div class="main">
		<div class="login-form">
			<van-form @submit="onSubmit">
				<van-cell-group inset>
					<van-field
						v-model="username"
						name="用户名"
						label="用户名"
						placeholder="用户名"
						:rules="[{ required: true, message: '请填写用户名' }]"
					></van-field>
					<van-field
						v-model="password"
						type="password"
						name="密码"
						label="密码"
						placeholder="密码"
						:rules="[{ required: true, message: '请填写密码' }]"
					/>
				</van-cell-group>
				<div style="margin: 16px">
					<van-button
						round
						block
						type="primary"
						native-type="submit"
						@click="login"
					>
						登录
					</van-button>
				</div>
			</van-form>
		</div>
		<span>去注册</span>
		<van-button
			type="primary"
			block
			class="zhuce"
			@click="goto('/register')"
			>快速注册</van-button
		>
	</div>
</template>
<script setup>
import { ref } from "vue"
import { useRouter } from "vue-router"
import { Form, Field, CellGroup, Button, showNotify } from "vant"

import { gotoLogin } from "../services/index"
import { usePhongStore } from "../stores/phone-store"

const username = ref("")
const password = ref("")
const onSubmit = (values) => {
	console.log("submit", values)
}
// 注册
const router = useRouter()

const phongStore = usePhongStore()

const goto = (path) => {
	router.push(path)
}

// 登录
// const login = async () => {
// 	const login = await gotoLogin(username.value, password.value)
// 	if (username.value === "" || password.value === "") {
// 		showNotify({ type: "primary", message: "请输入用户名和密码" })
// 	} else if (login.data.code !== "200") {
// 		showNotify({ type: "primary", message: "用户名或密码有误" })
// 	} else {
// 		// 保存用户token
// 		localStorage.setItem("token", login.data.data.token)
// 		// 保存用户userid
// 		localStorage.setItem("userid", login.data.data.userid)
// 		// 修改用户名 保持最新数据
// 		phongStore.setUserid(login.data.data.userid)
// 		showNotify({ type: "primary", message: "登录成功" })
// 		// router.push("/home")
// 		console.log(login)
// 	}
// }

// const emit = defineEmits(["getToken"])

const login = () => {
	gotoLogin(username.value, password.value).then((result) => {
		if (username.value == "" || password.value == "") {
			showNotify({ type: "primary", message: "请输入用户名和密码" })
		} else if (result.data.code == "200") {
			showNotify({ type: "primary", message: "登录成功" })
			localStorage.setItem("token", result.data.data.token)
			localStorage.setItem("userid", result.data.data.userid)
			phongStore.setUserid(result.data.data.userid)

			// emit("getToken", result.data.data.token)
			router.push('/personal')
			console.log(result)
		} else {
			showNotify({ type: "primary", message: "用户名或密码有误" })
		}
	})
}
</script>
<style scoped>
/* .main {
	height: 100vh;
} */
span {
	padding-left: 15px;
	font-size: 14px;
}
.zhuce {
	margin: 10px auto;
	width: 350px;
}
.login-form {
	margin-top: 20px;
}
</style>
